import datetime
import pytz
import coin.exchange.base.kr_rest.rest_client_base as rcb
import coin.exchange.deribit_v2.kr_rest.native_public_client as npubc

from coin.base.datetime_util import to_timestamp_int
from coin.proto.coin_market_query_pb2 import (
    ProductKlineElement,
    ProductKline,
)

DELAY_SECONDS = 4800

class DeribitPublicClient(object):
  def __init__(self):
    self.npubc = npubc.DeribitNativePublicClient()
    self._valid_period = ['KLINE_INTERVAL_1DAY']
    self._options_currencies = ['BTC', 'ETH', 'USDC']

  def query_history_kline(
      self, market_type, exchange, symbol, kline_period, start_time, end_time):
    assert exchange == 'Deribit', 'Invalid exchange: %s' % exchange
    assert symbol == 'TOTAL', 'Invalid symbol: %s' % symbol
    assert kline_period in self._valid_period, kline_period
    time_diff = (datetime.datetime.utcnow().replace(tzinfo=pytz.UTC) - end_time).total_seconds()
    assert time_diff <= DELAY_SECONDS, 'Deribit: only realtime 24h turnover supported'
    response_list = []
    for currency in self._options_currencies:
      response_list.extend(
        self.npubc.query_trading_summary_by_currency(market_type, currency).msg['result'])
    turnover_in_usd = sum([float(symbol['volume_usd']) for symbol in response_list])
    klines = [
        ProductKlineElement(
        turnover_in_usd=turnover_in_usd,
        kline_timestamp=to_timestamp_int(start_time))]
    product_kline = ProductKline(
        symbol='TOTAL',
        market_type=market_type,
        exchange=exchange,
        kline_period=kline_period,
        klines=klines)
    update = rcb.RestUpdate(
        to_timestamp_int(end_time),
        to_timestamp_int(end_time),
        product_kline)
    return update


if __name__ == "__main__":
  client = DeribitPublicClient()
  print(client.query_history_kline(
      'Options', 'Deribit', 'TOTAL', 'KLINE_INTERVAL_1DAY',
      datetime.datetime(2023, 5, 10).replace(tzinfo=pytz.UTC),
      datetime.datetime(2023, 5, 11).replace(tzinfo=pytz.UTC)).msg)
